package com.tsing.bms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tsing.bms.entity.MianTain;
import com.tsing.bms.mapper.MainTainMapper;
import com.tsing.bms.service.IMainTainService;
import com.tsing.bms.vo.req.IdReqVo;
import com.tsing.bms.vo.req.IdsReqVo;
import com.tsing.bms.vo.req.MainTainAddReqVo;
import com.tsing.bms.vo.req.MainTainUpdateReqVo;
import com.tsing.bms.vo.resp.MainTainRespVo;
import com.tsing.common.exceptions.BusinessException;
import com.tsing.common.exceptions.ServerException;
import com.tsing.common.utils.BeanCoperUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author TheTsing
 * @since 2021-03-29
 */
@Service
public class MainTainServiceImpl extends ServiceImpl<MainTainMapper, MianTain> implements IMainTainService {

    @Override
    public void addMainTain(MainTainAddReqVo reqVo) {
        if (0 != baseMapper.selectCount(new QueryWrapper<MianTain>().eq("name", reqVo.getName()))) {
            throw new BusinessException(ServerException.Proxy.NAME_HAVE_RELEVANCE);
        }
        MianTain mianTain = new MianTain();
        BeanUtils.copyProperties(reqVo, mianTain);
        baseMapper.insert(mianTain);
    }

    @Override
    public void deleteMainTain(IdsReqVo reqVo) {
        if (!StringUtils.isBlank(baseMapper.haveRelevance(reqVo.getIds()))) {
            throw new BusinessException(ServerException.Proxy.MAINTAIN_HAVE_RELEVANCE);
        }
        baseMapper.deleteBatchIds(reqVo.getIds());
    }

    @Override
    public MainTainRespVo getMainTain(IdReqVo reqVo) {
        MainTainRespVo mainTainRespVo = new MainTainRespVo();
        BeanUtils.copyProperties(baseMapper.selectById(reqVo.getId()), mainTainRespVo);
        return mainTainRespVo;
    }

    @Override
    public void updateMainTain(MainTainUpdateReqVo reqVo) {
        if (0 != baseMapper.selectCount(new QueryWrapper<MianTain>().eq("name", reqVo.getName())
                .ne("id", reqVo.getId()))) {
            throw new BusinessException(ServerException.Proxy.NAME_HAVE_RELEVANCE);
        }
        MianTain mianTain = new MianTain();
        BeanUtils.copyProperties(reqVo, mianTain);
        baseMapper.updateById(mianTain);
    }

    @Override
    public List<MainTainRespVo> mainTainList() {
        try {
            return BeanCoperUtil.copyObjects(baseMapper.selectList(null), MainTainRespVo.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
